<template>
  <div>
    <div style="height: 0px">
      <strong
        style="
          display: block;
          margin-top: 10px;
          text-align: center;
          font-size: 40px;
        "
        >雷暴大风外推</strong
      >
    </div>
    <div className="hello">
      <div className="box">
        <div className="map">
          <div id="map" ref="map"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useStore } from "vuex";
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import geoJson from "@/assets/yuegangao.json";
import regionStylesData from "@/assets/regionStyles.json";
import { getforecastData } from "@/api/user/forecast";
import L from "leaflet";
import { getDBZData } from "@/api/user/dbz";
import { getRainfallData } from "@/api/user/rainfall";
import { getQPFData } from "@/api/user/qpf";

export default {
  name: "forecast",
  props: {
    totalData: {
      default: null,
    },
    selectView: {
      default: null,
    },
  },
  created() {
    this.$emit("changeTimeIndex", 3);
    this.$emit("changeIsSelect2", true);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", true);
  },

  setup(props) {
    const totalData = reactive(props.totalData);
    // console.log(totalData, "111");
    const selectView = ref(props.selectView);
    watch(
      () => props.totalData,
      (newVal) => {
        console.log("totalData 发生了更改", newVal);
        totalData.value = newVal;
        params.year = newVal.startTime.getFullYear();
        params.month = newVal.startTime.getMonth() + 1;
        params.day = newVal.startTime.getDate();
        params.hour = newVal.startTime.getHours();
        params.minute = newVal.startTime.getMinutes();
        params.predict = newVal.predictTime;
        console.log("new params:", params);
        updateMap();
        changeMap();
      },
      { deep: true }
    );

    watch(
      () => props.selectView,
      (newVal) => {
        console.log("selectView 发生了更改", newVal);
        selectView.value = newVal;
        changeMap();
      },
      { deep: true }
    );

    let cooData = ref([]);
    let mymap;
    var geojsonForecast;
    var geojsonLayer;
    const store = useStore();
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10,
    };

    const COLORS1 = [
      "#00BEEC",
      "#00C0EE",
      "#00B0EF",
      "#009DF0",
      "#0089F0",
      "#0076F1",
      "#0062F2",
      "#004EF3",
      "#003CF4",
      "#003CF5",
      "#003CF6",
      "#0034F6",
      "#002DF6",
      "#0025F6",
      "#001EF6",
      "#0016F6",
      "#000FF6",
      "#0007F6",
      "#0000F6",
      "#0000F6",
      "#0000F6",
      "#001FD7",
      "#003FB9",
      "#005E9A",
      "#007E7C",
      "#009D5D",
      "#00BD3F",
      "#00DC20",
      "#00FC02",
      "#00FD01",
      "#00FE00",
      "#00F700",
      "#00F100",
      "#00EA00",
      "#00E400",
      "#00DD00",
      "#00D700",
      "#00D000",
      "#00CA00",
      "#00C900",
      "#00C800",
      "#00C100",
      "#00BA00",
      "#00B300",
      "#00AC00",
      "#00A500",
      "#009E00",
      "#009700",
      "#009000",
      "#009000",
      "#009000",
      "#1F9D00",
      "#3FAB00",
      "#5EB800",
      "#7EC600",
      "#9DD300",
      "#BDE100",
      "#DCEE00",
      "#FCFC00",
      "#FDFD00",
      "#FEFE00",
      "#FBF600",
      "#F8EF00",
      "#F5E700",
      "#F2E000",
      "#EFD800",
      "#ECD100",
      "#E9C900",
      "#E6C200",
      "#E6C100",
      "#E6C000",
      "#E9BA00",
      "#ECB400",
      "#EFAE00",
      "#F2A800",
      "#F5A200",
      "#F89C00",
      "#FB9600",
      "#FE9000",
      "#FE9000",
      "#FE9000",
      "#FE7E00",
      "#FE6C00",
      "#FE5A00",
      "#FE4800",
      "#FE3600",
      "#FE2400",
      "#FE1200",
      "#FE0000",
      "#FE0000",
      "#FE0000",
      "#F30000",
      "#E80000",
      "#DD0000",
      "#D20000",
      "#C70000",
      "#BC0000",
      "#B10000",
      "#A60000",
      "#A60000",
      "#A60000",
      "#9E0000",
      "#960000",
      "#8E0000",
      "#860000",
      "#7E0000",
      "#760000",
      "#6E0000",
      "#660000",
      "#650000",
      "#640000",
      "#77001F",
      "#8A003F",
      "#9D005E",
      "#B0007E",
      "#C3009D",
      "#D600BD",
      "#E900DC",
      "#FC00FC",
      "#FD00FD",
      "#FE00FE",
      "#F10AF7",
      "#E515F1",
      "#D81FEA",
      "#CC2AE4",
      "#BF34DD",
      "#B33FD7",
      "#A649D0",
      "#9A54CA",
      "#9954C9",
      "#9854C8",
      "#A469CE",
      "#B17ED5",
      "#BD93DB",
      "#CAA8E2",
      "#D6BDE8",
      "#E3D2EF",
      "#EFE7F5",
      "#FCFCFC",
      "#FDFDFD",
    ];
    const COLORS2 = ["#008000", "#ffff00", "#ffa500", "#ff0000"];
    const COLORS3 = [
      "#00ECEC",
      "#003CF6",
      "#0000F6",
      "#00FE00",
      "#00C800",
      "#009000",
      "#FEFE00",
      "#E6C000",
      "#FE9000",
      "#FE0000",
      "#A60000",
      "#640000",
      "#CC00FF",
      "#9854C8",
    ];

    let params = {
      year: 2023,
      month: 8,
      day: 1,
      hour: 3,
      minute: 42,
      predict: 6,
    };

    onMounted(() => {
      initMap();
      updateMap();
    });
    onUnmounted(() => {
      if (mymap) {
        mymap.remove();
        mymap = null;
      }
    });

    async function initMap() {
      const guangdongCenter = [23.125178, 113.280637];
      mymap = L.map("map", { attributionControl: false }).setView(
        guangdongCenter,
        7
      );

      // 切换底图
      //矢量地图
      const tileLayer1 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地图
      const tileLayer2 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //矢量地名
      const tileLayer3 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地名
      const tileLayer4 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      const baseMaps = {
        区划图: L.layerGroup([tileLayer1, tileLayer3]),
        地形图: L.layerGroup([tileLayer2, tileLayer4]),
      };
      tileLayer1.addTo(mymap);
      tileLayer3.addTo(mymap);
      L.control.layers(baseMaps).addTo(mymap);

      // 设置地图缩放范围
      mymap.setMinZoom(4);
      mymap.setMaxZoom(10);

      // 中国边界GeoJSON图层
      L.geoJSON(geoJson, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
          fillOpacity: 0.1,
        },
      }).addTo(mymap);

      function highlightFeature(e) {
        const layer = e.target;
        layer.setStyle({
          weight: 3,
          color: "#767676",
          fillColor: "#767676",
          dashArray: "",
          fillOpacity: 0.7,
        });
        layer.bringToFront();
      }

      function resetHighlight(e) {
        geojson.resetStyle(e.target);
      }

      // function zoomToFeature(e) {
      // 	map.fitBounds(e.target.getBounds());
      // }

      function onEachFeature(feature, layer) {
        layer.on({
          mouseover: highlightFeature,
          mouseout: resetHighlight,
          // click: zoomToFeature
        });
      }

      // 广东边界GeoJSON图层
      const geojson = L.geoJSON(regionStylesData, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
        },
        onEachFeature,
      }).addTo(mymap);

      //色标控件
      const legend = L.control({ position: "bottomright" });
      legend.onAdd = function (map) {
        const div = L.DomUtil.create("div", "legend");
        const grades1 = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75];
        const colors1 = [];
        const labels1 = [];

        const grades2 = [0, 0.8, 0.85, 0.9, 1];
        const colors2 = [];
        const labels2 = [];
        let from1, from2;
        let key = 0;
        for (let i = 0; i < COLORS1.length; i++) {
          if (i === 0) {
            colors1.push(
              `<i style="background: ${COLORS1[i]};width: 2.8px; margin-left:5px; height: 12px; float: left; opacity: 0.76;"></i>`
            );
          } else {
            colors1.push(
              `<i style="background: ${COLORS1[i]};width: 2.8px; height: 12px; float: left; opacity: 0.76;"></i>`
            );
          }
          if (i % 10 === 0) {
            from1 = grades1[key++];
            labels1.push(
              `<i style="width: 28px; height: 18px; text-align: left; float: left; font-style: normal;">${from1}</i>`
            );
          }
        }
        // 单独处理最后一个标签，以确保它位于最后一个色块的结束处
        labels1.push(
          `<i style="width: 8px; height: 18px; text-align: left; float: left; font-style: normal;">${
            grades1[grades1.length - 1]
          }</i>`
        );
        for (let i = 0; i < COLORS2.length; i++) {
          if (i === 0){
            colors2.push(
              `<i style="background: ${COLORS2[i]};width: 98px; margin-left:5px; height: 12px; float: left; opacity: 0.76;"></i>`
            );
          } else {
            colors2.push(
              `<i style="background: ${COLORS2[i]};width: 98px; height: 12px; float: left; opacity: 0.76;"></i>`
            );
          }
          from2 = grades2[i];
          labels2.push(
            `<i style="width: 96px; height: 18px; text-align: left; float: left; font-style: normal;">${from2}</i>`
          );
        }
        labels2.push(
            `<i style="width: 15px; height: 18px; text-align: left; float: left; font-style: normal;">${
              grades2[grades2.length - 1]
            }</i>`
          );
        div.innerHTML = `<div style="background-color: white; width: 420px; height: 120px; padding:4px">
                         <h3 style=" text-align: center;">雷暴大风</h3>
                         ${colors2.join("") + "<br>" + labels2.join("")}
                         <h3 style=" text-align: center;">降水估测（单位：mm）</h3>
                         ${colors1.join("") + "<br>" + labels1.join("")}
                         </div>`;
        return div;
      };
      legend.addTo(mymap);

      return mymap;
    }

    async function updateMap() {
      cooData.value = await fetchData(params);
      let data = cooData.value;
      // console.log(data);

      if (geojsonForecast) {
        mymap.removeLayer(geojsonForecast);
      }
      if (data === null) {
        showTopMessage("当前时间没有（识别点）相关数据", 2000);
      } else {
        const geojson = data[0].coo;
        function getColor2(d) {
          return d >= 0.9
            ? COLORS2[3]
            : d >= 0.85
            ? COLORS2[2]
            : d >= 0.8
            ? COLORS2[1]
            : COLORS2[0];
        }
        function createMarker(feature, latlng) {
          // 定义矩形的经度和纬度尺寸
          var rectangleWidth = 0.15;
          var rectangleHeight = 0.15;
          var centerCoordinates = feature.geometry.coordinates;
          // console.log(centerCoordinates);
          // 计算矩形的边界范围
          var southWest = L.latLng(
            centerCoordinates[1] - rectangleHeight / 2,
            centerCoordinates[0] - rectangleWidth / 2
          );
          var northEast = L.latLng(
            centerCoordinates[1] + rectangleHeight / 2,
            centerCoordinates[0] + rectangleWidth / 2
          );
          var bounds = L.latLngBounds(southWest, northEast);

          // 返回一个矩形标记
          return L.rectangle(bounds, {
            color: getColor2(feature.properties.value),
            fillOpacity: 0,
            weight: 2,
          });
        }
        mymap.createPane('Pane1');
        mymap.getPane('Pane1').style.zIndex = 250;
        // 雷暴大风点
        geojsonForecast = L.geoJSON(geojson, {
          pointToLayer: createMarker,
          pane: 'Pane1'
        });
        geojsonForecast.addTo(mymap);
      }
    }

    async function changeMap() {
      let adddata;
      mymap.createPane('Pane2');
      mymap.getPane('Pane2').style.zIndex = 300;
      if (selectView.value === "1") {
        adddata = await fetchDBZData(params);

        if (adddata === null) {
          showTopMessage("当前时间没有（视图）相关数据", 2000);
        } else {
          let blob = new Blob([adddata.data], { type: "image/png" });
          const imageUrl = URL.createObjectURL(blob); // 将Blob转换为URL
          if (geojsonLayer) {
            mymap.removeLayer(geojsonLayer);
          }
          const imageBounds = [
            [27, 108.5],
            [18.2, 119],
          ];
          // 使用L.imageOverlay在指定范围内添加图片到地图上
          geojsonLayer = L.imageOverlay(imageUrl, imageBounds);
          geojsonLayer.addTo(mymap);
        }
      } else if (selectView.value === "2") {
        adddata = await fetchRainfallData(params);

        if (adddata === null) {
          showTopMessage("当前时间没有（视图）相关数据", 2000);
        } else {
          let blob = new Blob([adddata.data], { type: "image/png" });
          const imageUrl = URL.createObjectURL(blob); // 将Blob转换为URL
          
          if (geojsonLayer) {
            mymap.removeLayer(geojsonLayer);
          }
          const imageBounds = [
            [27, 108.5],
            [18.2, 119],
          ];
          // 使用L.imageOverlay在指定范围内添加图片到地图上
          geojsonLayer = L.imageOverlay(imageUrl, imageBounds);
          geojsonLayer.addTo(mymap);
        }
      } else if (selectView.value === "3") {
        adddata = await fetchQPFData(params);
    
        if (adddata === null) {
          showTopMessage("当前时间没有（视图）相关数据", 2000);
        } else {
          let blob = new Blob([adddata.data], { type: "image/png" });
          const imageUrl = URL.createObjectURL(blob); // 将Blob转换为URL

          if (geojsonLayer) {
            mymap.removeLayer(geojsonLayer);
          }
          const imageBounds = [
            [27, 108.5],
            [18.2, 119],
          ];
          // 使用L.imageOverlay在指定范围内添加图片到地图上
          geojsonLayer = L.imageOverlay(imageUrl, imageBounds);
          geojsonLayer.addTo(mymap);
        }
      }
    }

    async function fetchData(params) {
      try {
        let Data = await getforecastData(params); // 使用接口文件中的函数获取数据
        return Data;
      } catch (error) {
        console.error("Error fetching COO data:", error);
        return null;
      }
    }
    async function fetchDBZData(params) {
      try {
        const Data = await getDBZData(params);
        return Data;
      } catch (error) {
        console.error("Error fetching COO data:", error);
        return null;
      }
    }
    async function fetchRainfallData(params) {
      try {
        const Data = await getRainfallData(params);
        return Data;
      } catch (error) {
        console.error("Error fetching COO data:", error);
        return null;
      }
    }
    async function fetchQPFData(params) {
      try {
        const Data = await getQPFData(params);
        return Data;
      } catch (error) {
        console.error("Error fetching COO data:", error);
        return null;
      }
    }

    function showTopMessage(message, duration) {
      // 创建一个提示元素
      const messageElement = document.createElement("div");
      messageElement.className = "top-message";
      messageElement.textContent = message;

      // 将提示元素添加到页面的顶部
      document.body.appendChild(messageElement);

      // 设置定时器，在一定时间后自动隐藏提示
      setTimeout(() => {
        messageElement.style.opacity = "0"; // 渐变消失
        setTimeout(() => {
          document.body.removeChild(messageElement); // 删除提示元素
        }, 1000); // 在渐变结束后删除元素
      }, duration);

      // 自定义样式
      messageElement.style.position = "fixed";
      messageElement.style.top = "100px";
      messageElement.style.left = "42%";
      messageElement.style.width = "300px";
      messageElement.style.borderRadius = "4px";
      messageElement.style.backgroundColor = "#88bffa";
      messageElement.style.color = "#fff";
      messageElement.style.padding = "10px 0";
      messageElement.style.textAlign = "center";
      messageElement.style.transition = "opacity 1s ease-in-out";
    }

    return {
      totalData,
      selectView,
    };
  },
};
</script>

<style scoped lang="scss">
.time-picker-fixed {
  position: fixed;
  top: 90%; /* 垂直居中 */
  left: 50%; /* 水平居中 */
  transform: translate(-50%, -50%); /* 居中偏移 */
  width: 1200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background-color: transparent;
}

.time-picker {
  justify-content: center;
  width: 400px;
  display: flex;
  flex-direction: row; /* 水平布局 */
  align-items: center;
  border: 3px solid #007bff;
  padding: 20px;
  border-radius: 8px;
  background-color: #f0f0f0;
}

.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (min-width: 700px) {
  .map {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #map {
      width: 100%;
      height: 65vh;
    }
  }
}

.custom-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.custom-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.custom-button:hover {
  background-color: #0056b3;
}
</style>
